package com.yang.testdowload;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download")
public class TestDowLoad01 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        String path = req.getServletContext().getRealPath("/download/");
        File file = new File(path + filename);
        if(file.exists()||file.isFile()){
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment; filename="+filename);
            FileInputStream fi = new FileInputStream(file);
            ServletOutputStream sos = resp.getOutputStream();
            int filebyte = -1;
            while((filebyte = fi.read())!=-1){
                sos.write(filebyte);
            }
        }else {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("文件不存在!");
        }
    }
}
